<?
ob_start("ob_gzhandler");
require "include/bittorrent.php";
dbconn(true);

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
	$choice = $_POST["choice"];
	if ($CURUSER && $choice != "" && $choice < 256 && $choice == floor($choice))
	{
		$choice = (int)$choice;
		$res = query("SELECT * FROM polls ORDER BY added DESC LIMIT 1") or sqlerr();
		$arr = mysql_fetch_assoc($res) or die("No poll");
		$pollid = $arr["id"];
		$userid = $CURUSER["id"];
		$res = query("SELECT * FROM pollanswers WHERE pollid=$pollid && userid=$userid") or sqlerr();
		$arr = mysql_fetch_assoc($res);
		if ($arr) 
			die("Dupe vote");
		query("INSERT INTO pollanswers VALUES(0, $pollid, $userid, $choice)") or sqlerr();
		if (mysql_affected_rows() != 1)
			error("An error occured. Your vote has not been counted.");
		header("Location: $SITEURL/");
		die;
	}
    	else
	{
		$user = $CURUSER['id'];
		if($_GET["act"] == "Arcade")
		{
			if($_POST['gname'] == "asteroids")
			{
				$game = 1;
				$level = 1;
				$score = (int)$_POST['score'];
			}
			else if($_POST['gname'] == "breakout")
			{
				$game = 2;
				$level = 1;
				$score = (int)$_POST['gscore'];
	  		}
			else if($_POST['gname'] == "invaders")
			{
				$game = 3;
				$level = 1;
				$score = (int)$_POST['score'];
			}
			else if($_POST['gname'] == "pacman")
			{
				$game = 4;
				$level = 1;
				$score = (int)$_POST['gscore'];
			}
			else if($_POST['gname'] == "moonlander")
			{
				$game = 5;
				$level = 1;
				$score = (int)$_POST['gscore'];
			}
			else if($_POST['gname'] == "snake")
			{
				$game = 6;
				if($_POST['levelName'] == "LEVEL: SLUG")
					$level = 1;
				else if($_POST['levelName'] == "LEVEL: WORM")
					$level = 2;
				else if($_POST['levelName'] == "LEVEL: PYTHON")
					$level = 3;
				$score = (int)$_POST['score'];
			}
			else if($_POST['gname'] == "tetris")
			{
				$game = 7;
				$level = (int)$_POST['level'];
				$score = (int)$_POST['gscore'];
			}
			query("INSERT INTO `highscores` ( `ID` , `game` , `user` , `level` , `score` ) VALUES ( '', '".$game."', '".$user."', '".$level."', '".$score."')") or die(mysql_error());
			header("Location: $SITEURL/highscores.php");
			die;
		}
		else
			error("An error occurred while posting to the index page.");
	}
}

/*
$a = @mysql_fetch_assoc(@query("SELECT id,username FROM users WHERE status='confirmed' ORDER BY id DESC LIMIT 1")) or die(mysql_error());
if ($CURUSER)
  $latestuser = "<a href=userdetails.php?id=" . $a["id"] . ">" . $a["username"] . "</a>";
else
  $latestuser = $a['username'];
*/


$registered = get_row_count("users");
$verified = get_row_count("users", "WHERE status='confirmed'");
$forumposts = get_row_count("posts");
$forumtopics = get_row_count("topics");
$torrents = get_row_count("torrents");
$seeders = get_row_count("peers", "WHERE seeder='yes'");
$leechers = get_row_count("peers", "WHERE seeder='no'");
//$dead = get_row_count("torrents", "WHERE visible='no'");

if ($leechers == 0)
  $ratio = 0;
else
  $ratio = round($seeders / $leechers * 100);

$peers = $seeders + $leechers;


$dt = time() - 600;
$dt = sqlesc(get_date_time($dt));
$onlineusers = get_row_count("users", "WHERE last_access >= $dt");



$res = query("SELECT SUM(uploaded) as totalupload FROM users WHERE status='confirmed'") or sqlerr();
$arr = mysql_fetch_assoc($res);
$uploaded = $arr["totalupload"];




stdhead();
//echo "<font class=small>Welcome to our newest member, <b>$latestuser</b>!</font>\n";

print("<table width=750 class=main border=0 cellspacing=0 cellpadding=0><tr><td class=embedded>");
print("<h2>Recent news");
if ($CURUSER)
{
if (get_user_class() >= UC_ADMINISTRATOR)
	print(" - <font class=small>[<a class=altlink href=news.php><b>News page</b></a>]</font>");
print("</h2>\n");
$res = query("SELECT * FROM news WHERE ADDDATE(added, INTERVAL 14 DAY) > NOW() ORDER BY added DESC LIMIT 4") or sqlerr(__FILE__, __LINE__);
if (mysql_num_rows($res) > 0)
{
	print("<table width=100% border=1 cellspacing=0 cellpadding=10><tr><td class=text>\n<ul>");
	while($array = mysql_fetch_array($res))
	{
		print("<li>" . date("Y-m-d",strtotime($array['added'])) . " - " . format_comment($array['body'],false));
        	if (get_user_class() >= UC_ADMINISTRATOR)
        	{
    			print(" <font size=\"-2\">[<a class=altlink href=news.php?action=edit&newsid=" . $array['id'] . "&returnto=" . urlencode($_SERVER['PHP_SELF']) . "><b>E</b></a>]</font>");
    			print(" <font size=\"-2\">[<a class=altlink href=news.php?action=delete&newsid=" . $array['id'] . "&returnto=" . urlencode($_SERVER['PHP_SELF']) . "><b>D</b></a>]</font>");
        	}
        	print("</li>");
 	}
   	print("</ul></td></tr></table>\n");
}
}
else
{
print("</h2>\n");
print("<table width=100% border=1 cellspacing=0 cellpadding=10><tr><td class=text>\n<ul>");
print("<li>Welcome to $SITENAME. Please signup or login at the top.</li>");
print("</ul></td></tr></table>\n");
}



/*
<h2>Active users</h2>
<table width=100% border=1 cellspacing=0 cellpadding=10><tr><td class=text>
<?=$activeusers?>
</td></tr></table>
*/


if ($CURUSER)
{
  // Get current poll
  $res = query("SELECT * FROM polls ORDER BY added DESC LIMIT 1") or sqlerr();
  if($pollok=(mysql_num_rows($res)))
  {
  	$arr = mysql_fetch_assoc($res);
  	$pollid = $arr["id"];
  	$userid = $CURUSER["id"];
  	$question = $arr["question"];
  	$o = array($arr["option0"], $arr["option1"], $arr["option2"], $arr["option3"], $arr["option4"],
    	$arr["option5"], $arr["option6"], $arr["option7"], $arr["option8"], $arr["option9"],
    	$arr["option10"], $arr["option11"], $arr["option12"], $arr["option13"], $arr["option14"],
    	$arr["option15"], $arr["option16"], $arr["option17"], $arr["option18"], $arr["option19"]);
	$topic_id = $arr["topic_id"];

  // Check if user has already voted
  	$res = query("SELECT * FROM pollanswers WHERE pollid=$pollid AND userid=$userid") or sqlerr();
  	$arr2 = mysql_fetch_assoc($res);
  }

  print("<h2>Poll");

  if (get_user_class() >= UC_MODERATOR)
  {
  	print("<font class=small>");
		print(" - [<a class=altlink href=makepoll.php?returnto=main><b>New</b></a>]\n");
		if($pollok) {
		print(" - [<a class=altlink href=polloverview.php?id=$arr[id]><b>Overview</b></a>]\n");
  		print(" - [<a class=altlink href=makepoll.php?action=edit&pollid=$arr[id]&returnto=main><b>Edit</b></a>]\n");
			print(" - [<a class=altlink href=polls.php?action=delete&pollid=$arr[id]&returnto=main><b>Delete</b></a>]");
		}
		print("</font>");
	}
	print("</h2>\n");
	if($pollok) {
		print("<table width=100% border=1 cellspacing=0 cellpadding=10><tr><td align=center>\n");
  	print("<table class=main border=1 cellspacing=0 cellpadding=0><tr><td class=text>");
  	print("<p align=center><b>$question</b></p>\n");
  	$voted = $arr2;
  	if ($voted)
  	{
    	// display results
      	$uservote = $arr2["selection"];

			// we reserve 255 for blank vote.
    	$res = query("SELECT selection FROM pollanswers WHERE pollid=$pollid AND selection < 20") or sqlerr();

    	$tvotes = mysql_num_rows($res);

    	$vs = array(); // array of
    	$os = array();

    	// Count votes
    	while ($arr2 = mysql_fetch_row($res))
      	$vs[$arr2[0]] += 1;

    	reset($o);
    	for ($i = 0; $i < count($o); ++$i)
      	if ($o[$i])
        	$os[$i] = array($vs[$i], $o[$i], $i);

    	function srt($a,$b)
    	{
      	if ($a[0] > $b[0]) return -1;
      	if ($a[0] < $b[0]) return 1;
      	return 0;
    	}

    	// now os is an array like this: array(array(123, "Option 1"), array(45, "Option 2"))
    	if ($arr["sort"] == "yes")
    		usort($os, srt);

    	print("<table class=main width=100% border=0 cellspacing=0 cellpadding=0>\n");



	$largest = 0;
    	for($i=0;$a=$os[$i];$i++)
    	{
      	if ($a[0] > $largest)
	$largest = $a[0];
    	}
	if ($largest != '0')
	$scale = $tvotes/$largest;
	else
	$scale = 1;




    	for($i=0;$a=$os[$i];$i++)
    	{
      	if ($a[2] == $uservote)
        	$a[1] .= "&nbsp;*";
      	if ($tvotes == 0)
      		$p = 0;
      	else
      		$p = round($a[0] / $tvotes * 100);
      	if ($i % 2)
        	$c = "";
      	else
        	$c = " bgcolor=#ECE9D8";
      	print("<tr><td width=1% class=embedded$c><nobr>" . $a[1] . "&nbsp;&nbsp;</nobr></td><td width=99% class=embedded$c>" .
        	"<img src=/pic/bar_left.gif><img src=/pic/bar.gif height=9 width=" . ($p * 2 * $scale) .
        	"><img src=/pic/bar_right.gif> $p%</td></tr>\n");
    	}

    	print("</table>\n");
			$tvotes = number_format($tvotes);
	if (get_user_class() >= UC_MODERATOR)
	{
	print("<p align=center><a class=altlink href=polloverview.php?id=$arr[id]><b>Votes: $tvotes</b></a></p>\n");
	}
	else
	{
    	print("<p align=center>Votes: $tvotes</p>\n");
	}
  	}
  	else
  	{
    	print("<form method=post action=index.php>\n");
    	$i = 0;
    	while ($a = $o[$i])
    	{
      	print("<input type=radio name=choice value=$i>$a<br>\n");
      	++$i;
    	}
    	print("<br>");
    	print("<input type=radio name=choice value=255>Blank vote (a.k.a. \"I just want to see the results!\")<br>\n");
    	print("<p align=center><input type=submit value='Vote!' class=btn></p>");
  	}
?>
</td></tr></table>
<? 
    print("<p align=center><a href=polls.php>Previous polls</a> | <a href=forums.php?action=viewtopic&topicid=$topic_id>Discuss Poll</a></p>\n");
?>
</td></tr></table>

<?
	} else {
		echo "<table width=100% border=1 cellspacing=0 cellpadding=10><tr><td align=center>\n";
  	echo "<table class=main border=1 cellspacing=0 cellpadding=0><tr><td class=text>";
  	echo"<p align=center><H3>No Active Polls</h3></p>\n";
  	echo "</td></tr></table></td></tr></table>";
	}
}
?>

<?

if ($CURUSER)
{
if ($CURUSER["hide_feed"] != "yes")
{
print("<h2>Friend feed</h2>");
print("<table width=100% border=1 cellspacing=0 cellpadding=10><tr><td align=center>");
print("<table class=main border=1 cellspacing=0 cellpadding=0><tr><td class=text>");
$numfriends = get_row_count("friends","WHERE userid=$CURUSER[id]");
if (!$numfriends)
print("<p align=center><b>You haven't added any <a href=friends.php>friends</a> yet!</b></p>");
else
{
print("<p align=center><b>Recent <a href=friends.php>friend</a> activity:</b></p>");
print("<table class=main width=100% border=0 cellspacing=0 cellpadding=0>\n");
$res2 = query("SELECT * FROM ( SELECT snatched.added, 'download' as type, userid as friendid, torrentid as activityid, username as friendname, name as activityname FROM snatched JOIN users ON userid = users.id JOIN torrents ON torrentid = torrents.id WHERE userid IN ( SELECT friendid FROM friends WHERE userid=$CURUSER[id] ) " . 
"UNION ALL SELECT torrents.added, 'upload' as type, owner as friendid, torrents.id as activityid, username as friendname, name as activityname FROM torrents JOIN users ON owner = users.id WHERE owner IN ( SELECT friendid FROM friends WHERE userid=$CURUSER[id] ) " . 
"UNION ALL SELECT posts.added, 'post' as type, posts.userid as friendid, topicid as activityid, username as friendname, subject as activityname FROM posts JOIN users ON posts.userid = users.id JOIN topics ON topicid = topics.id JOIN forums on topics.forumid = forums.id WHERE posts.userid IN ( SELECT friendid FROM friends WHERE userid=$CURUSER[id] ) AND $CURUSER[class] >= minclassread " . 
"UNION ALL SELECT comments.added, 'comment' as type, user as friendid, torrent as activityid, username as friendname, name as activityname FROM comments JOIN users ON user = users.id JOIN torrents ON torrent = torrents.id WHERE user IN ( SELECT friendid FROM friends WHERE userid=$CURUSER[id] ) ) t1 WHERE ADDDATE(added, INTERVAL 7 DAY) > NOW() ORDER BY added DESC LIMIT 10");
if (mysql_num_rows($res2) == 0)
	print("<tr><td class=clear align=center>Nothing</td></tr>");
else
{
	while ($arr2 = mysql_fetch_assoc($res2))
	{
		$type = $arr2['type'];
		
		if (strlen($arr2[activityname]) > 50)
		{
			$name = substr($arr2[activityname],0,47);
			$name .= "...";
		}
		else
			$name = $arr2[activityname];
			
		if ($type == "download")
			print("<tr><td style=\"border:none;padding:1px;font-weight:bold;text-align:left;\"><a class=altlink_black href=userdetails.php?id=$arr2[friendid]>$arr2[friendname]</a> <span style=\"color:#900900\">downloaded</span> <a class=altlink_black title=\"" . htmlspecialchars($arr2["activityname"]) . "\" href=details.php?id=$arr2[activityid]>" . htmlspecialchars($name) . "</a></td></tr>\n");
		else if ($type == "upload")
			print("<tr><td style=\"border:none;padding:1px;font-weight:bold;text-align:left;\"><a class=altlink_black href=userdetails.php?id=$arr2[friendid]>$arr2[friendname]</a> <span style=\"color:#009900\">uploaded</span> <a class=altlink_black title=\"" . htmlspecialchars($arr2["activityname"]) . "\" href=details.php?id=$arr2[activityid]>" . htmlspecialchars($name) . "</a></td></tr>\n");
		else if ($type == "post")
			print("<tr><td style=\"border:none;padding:1px;font-weight:bold;text-align:left;\"><a class=altlink_black href=userdetails.php?id=$arr2[friendid]>$arr2[friendname]</a> <span style=\"color:#007799\">posted in</span> <a class=altlink_black title=\"" . htmlspecialchars($arr2["activityname"]) . "\" href=forums.php?action=viewtopic&topicid=$arr2[activityid]>" . htmlspecialchars($name) . "</a></td></tr>\n");
		else
			print("<tr><td style=\"border:none;padding:1px;font-weight:bold;text-align:left;\"><a class=altlink_black href=userdetails.php?id=$arr2[friendid]>$arr2[friendname]</a> <span style=\"color:#003399\">commented on</span> <a class=altlink_black title=\"" . htmlspecialchars($arr2["activityname"]) . "\" href=details.php?id=$arr2[activityid]>" . htmlspecialchars($name) . "</a></td></tr>\n");
	}
}
print("</table>");
}
print("</td></tr></table>");
print("</td></tr></table>\n");
}
}

?>

<?
print("<h2>Stats");
if (get_user_class() >= UC_MODERATOR)
print(" - <font class=small>[<a class=altlink href=stats.php><b>Stats page</b></a>]</font>");
print("</h2>");
?>

<table width=100% border=1 cellspacing=0 cellpadding=10><tr><td align=center>
<table cellspacing=0 cellpadding=5>
<tr><td class=clearpadded>
<table class=main border=1 cellspacing=0 cellpadding=5>
<tr><td class=rowhead>Maximum users</td><td align=right><?=number_format($maxusers)?></td></tr>
<tr><td class=rowhead>Registered users</td><td align=right><?=number_format($registered)?></td></tr>
<tr><td class=rowhead>Confirmed users</td><td align=right><?=number_format($verified)?></td></tr>
<tr><td class=rowhead>Online users</td><td align=right><?=number_format($onlineusers)?></td></tr>
<tr><td class=rowhead>Forum posts</td><td align=right><?=number_format($forumposts)?></td></tr>
<tr><td class=rowhead>Forum topics</td><td align=right><?=number_format($forumtopics)?></td></tr>
</table>
</td>
<td class=clearpadded>
<table class=main border=1 cellspacing=0 cellpadding=5>
<tr><td class=rowhead>Torrents</td><td align=right><?=number_format($torrents)?></td></tr>
<tr><td class=rowhead>Total peers</td><td align=right><?=number_format($peers)?></td></tr>
<tr><td class=rowhead>Seeders</td><td align=right><?=number_format($seeders)?></td></tr>
<tr><td class=rowhead>Leechers</td><td align=right><?=number_format($leechers)?></td></tr>
<tr><td class=rowhead>S/L ratio (%)</td><td align=right><?=number_format($ratio)?></td></tr>
<tr><td class=rowhead>Uploaded</td><td align=right><?=bytesize($uploaded)?></td></tr>
</table>
</td>
</tr></table>
</td></tr></table>

<? /*
<h2>Server load</h2>
<table width=100% border=1 cellspacing=0 cellpadding=10><tr><td align=center>
<table class=main border=0 width=402><tr><td style='padding: 0px; background-image: url(/pic/loadbarbg.gif); background-repeat: repeat-x'>
<? $percent = min(100, round(exec('ps ax | grep -c apache') / 256 * 100));
if ($percent <= 70) $pic = "loadbargreen.gif";
elseif ($percent <= 90) $pic = "loadbaryellow.gif";
else $pic = "loadbarred.gif";
$width = $percent * 4;
print("<img height=15 width=$width src=\"/pic/$pic\" alt='$percent%'>"); ?>
</td></tr></table>
</td></tr></table>
*/ ?>

<p align=center><font class=small>
Disclaimer: None of the files shown here are actually hosted on this server. The links are provided solely by this site's users. The administrator of this site cannot be held responsible for what its users post, or any other actions of its users. You may not use this site to distribute or download any material when you do not have the legal rights to do so. It is your own responsibility to adhere to these terms.</font></p>


</td></tr></table>

<?
stdfoot();
?>